import logging
import os
import time
from functools import wraps
from pathlib import Path

class Logger:
    _loggers = {}
    
    @classmethod
    def _get_base_dir(cls):
        """获取项目根目录"""
        # 从当前文件向上查找，直到找到项目根目录
        current_path = Path(__file__).resolve()
        # 向上查找三级目录（common/utils/logger.py -> common/utils -> common -> 项目根目录）
        return current_path.parent.parent.parent
    
    @classmethod
    def get_logger(cls, name='default'):
        """
        获取logger实例
        如果logger不存在则创建新的logger实例并配置
        
        日志文件存储位置:
        - 默认日志: BASE_DIR/logs/default.log
        - 操作日志: BASE_DIR/logs/operation.log
        - 错误日志: BASE_DIR/logs/error.log
        """
        if name not in cls._loggers:
            logger = logging.getLogger(name)
            
            # 防止日志重复
            logger.propagate = False
            
            # 如果logger还没有处理器，添加文件和控制台处理器
            if not logger.handlers:
                # 确保日志目录存在
                base_dir = cls._get_base_dir()
                log_dir = os.path.join(base_dir, 'logs')
                os.makedirs(log_dir, exist_ok=True)
                
                # 文件处理器
                file_handler = logging.FileHandler(
                    os.path.join(log_dir, f'{name}.log'),
                    encoding='utf-8'
                )
                file_formatter = logging.Formatter(
                    '%(asctime)s [%(levelname)s] %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S'
                )
                file_handler.setFormatter(file_formatter)
                logger.addHandler(file_handler)
                
                # 控制台处理器
                console_handler = logging.StreamHandler()
                console_formatter = logging.Formatter(
                    '\033[32m%(asctime)s\033[0m [\033[34m%(levelname)s\033[0m] %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S'
                )
                console_handler.setFormatter(console_formatter)
                logger.addHandler(console_handler)
                
                # 设置日志级别
                logger.setLevel(logging.INFO)
            
            cls._loggers[name] = logger
        return cls._loggers[name]

    @classmethod
    def info(cls, message, name='default'):
        """
        记录info级别日志
        """
        cls.get_logger(name).info(message)

    @classmethod
    def error(cls, message, name='default'):
        """
        记录error级别日志
        """
        cls.get_logger(name).error(message)

    @classmethod
    def warning(cls, message, name='default'):
        """
        记录warning级别日志
        """
        cls.get_logger(name).warning(message)

    @classmethod
    def debug(cls, message, name='default'):
        """
        记录debug级别日志
        """
        cls.get_logger(name).debug(message)

def log_operation(operation_type):
    """
    操作日志装饰器
    """
    def decorator(func):
        @wraps(func)
        def wrapper(request, *args, **kwargs):
            start_time = time.time()
            response = func(request, *args, **kwargs)
            end_time = time.time()
            
            # 获取用户信息
            user = request.user.username if hasattr(request, 'user') else 'anonymous'
            
            # 记录操作日志
            log_data = {
                'user': user,
                'operation_type': operation_type,
                'path': request.path,
                'method': request.method,
                'params': request.GET if request.method == 'GET' else request.POST,
                'execution_time': f"{(end_time - start_time):.3f}s",
                'ip': request.META.get('REMOTE_ADDR'),
                'status_code': response.status_code if hasattr(response, 'status_code') else None
            }
            
            Logger.info(f"Operation Log: {log_data}", name='operation')
            return response
        return wrapper
    return decorator 